package com.jghz.framework.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DownloadUtils {

	private final static Logger logger = LoggerFactory.getLogger(DownloadUtils.class);

	public static void download(HttpServletResponse response, File file, String fileName)
			throws UnsupportedEncodingException {
		response.setContentType("application/octet-stream");// 设置文件输出类型
		// new String(fileName.getBytes("utf-8"), "ISO8859-1")

		String filnalFileName = "";
		if (StringUtils.isBlank(fileName)) {
			filnalFileName = file.getName();
		} else {
			filnalFileName = fileName;
		}
		response.setHeader("Content-disposition",
				"attachment; filename=" + new String(filnalFileName.getBytes("utf-8"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(file.length()));// 设置输出长度

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(file));// 获取输入流
			bos = new BufferedOutputStream(response.getOutputStream());// 输出流

			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}

		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			// 关闭流
			try {
				bis.close();
				bos.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
	}

}
